<template>
    <div class="liveInteractive">
        <header>
            <i @click="goBack()"></i>
            <!-- <div class="vdo"> -->
                <!-- <img src="../../img/33.jpg" width="100%" height="280" /> -->
                <!-- <video :src="courseObj.url" controls></video> -->
            <!-- </div> -->
      </header>
      <div class='controls'>
          <img @click='goFullLive' src="../../image/icon_screen.png" width='17' alt="">
      </div>
        <div class="chat">
          <div class="title">
              <span>主讲老师: {{courseObj.username}}</span>
              <p>
                  <!-- <img src="../../img/33.jpg" width="20" height="20" />
                  <img src="../../img/4de25b51-1ab1-4c70-8a82-e765a0c7efbb.jpg" width="20" height="20" />
                  <img src="../../img/1.jpg" width="20" height="20" /> -->
                   在线人数: {{liveObj.online_num}}人
              </p>
          </div>
          <div class="border-6"></div>
          <div class="gradebox">
              <!-- 评价图标 -->
              <img @click="isShowMc=true" class="commentIcon" src="../../image/comment.png" width="22" height="22" alt="">
              <!-- <img @click="aa" class="commentIcon" src="../../image/comment.png" width="22" height="22" alt=""> -->
          </div>
          <div class="border-6"></div>
          <Loadmore
              :bottom-method="loadBottom"
              :bottom-all-loaded="allLoaded"
              ref="loadmore"
              :autoFill="false"
          >
            <ul>
                <li v-for='(item,index) in orderByTime' :key='index'>
                    <a>{{item.username}} <time>{{item.time | formatDate}}</time></a>
                    <div>
                        <i></i>
                        {{item.content}}
                    </div>
                </li>
            </ul>
          </Loadmore>
        </div>
      <div class="mc" v-show="isShowMc" @click.stop='isShowMc=false'>
          <div class='bottom' @click.stop='isShowMc=true'>
              <div class="input">
                   <img src="../../image/icon_keyboard.png" width="25" height="25" alt="">
                  <input type="text" placeholder="我也来聊几句..." v-model='obj.content'>
              </div>
              <a class="send" @click.stop='sendComment()'>
                  提   交
              </a>
          </div>
      </div>
  </div>
</template>
<script>

  import {Loadmore} from 'mint-ui';
  import {formatDate} from '../../common/date.js'
  export default {
      data() {
          return {
              list: [],
              obj: {
                  live_id: '',
                  userid: '',
                  content: '',    //评价内容     
              },
              liveObj: {},
              gradeScore: 5,    //综合评分
              chatContent: '', //我发表的评论
              gradeValue: 5, //星级打分
              isShowMc: false,  //是否显示评价
              courseObj: {}, //课程详情
              sentPage:{
                page : 1,//分页累加
              },//接口入参
              totalNum: 0, //总数据条数
              allLoaded: false,                   //分页数据是否已经加载完毕
          }
      },
      computed: {
          orderByTime() {
              var self = this;
              const list = _.orderBy(this.list, 'time','desc'); //排序 要引入lodash模块 默认升序
              return list;
          },
      },
      filters: {
          formatDate(time){
              var now = formatDate(new Date(),'yyyy-MM-dd hh:mm');
              var nowHeader = now.substring(0,10);
              var commentHeader = time.substring(0,10);
              // 如果是当天 就不显示评论的年月日
              if(nowHeader == commentHeader) {
                  return time.substring(10);
              }else {
                  return time;
              }
          },
      },
      components: {
          Loadmore
      },
      methods: {
          // 直播全屏
          goFullLive() {
              const  url = 'http://192.168.0.149:8080/t/tmp/hls/123.m3u8'
              this.$router.push({name:'fullLive',query: url});
          },
          goBack() {
              this.$router.back();
          },
          //在线人数加一或减一
          getOnline_num(status) {   // 0 表示减1 1表示加1
              this.$api.get(this.$api.baseURLSchool,"select_cid/live_room/"+this.obj.live_id,{},r => {
                  // console.log(r);
                  if(r.data.ret == 1) {
                      this.liveObj = r.data.info;
                      console.log(typeof(this.liveObj.online_num));
                      if(status == 1) {
                          console.log(11);
                          this.liveObj.online_num = this.liveObj.online_num*1 + 1;
                      } else {
                          console.log(22);
                          this.liveObj.online_num = this.liveObj.online_num*1 - 1;
                      }
                      this.$api.post(this.$api.baseURLSchool,"updatedata/live_room/edit",this.liveObj,r => {
                          console.log(r);
                      },err => {
                          console.log(err);
                      })
                  }
              },err => {
                  console.log(err);
              })
          },
          init() {    
              this.obj.live_id = this.$route.query.id;
              this.obj.userid = localStorage.getItem("loginMobile");
          },
          showVideo() {
              $('#video').show();
          },
          //获取当前直播的评价
          getCommentList(params) {
              this.$api.post(this.$api.baseURLSchool,"selecttype_view/view_live_comment_user/0?live_id="+this.obj.live_id,params,r => {
                  // console.log(r);
                  this.totalNum = r.data.records;
                  if(this.sentPage.page==1) {
                      this.list = r.data.rows;
                  }else {
                      this.list = this.list.concat(r.data.rows);
                  }
                  if(r.data.rows.length == 0&&this.sentPage.page>1) {
                      this.$utils._toast("暂无更多评价");
                  }
                  if(this.totalNum == this.list.length) {
                      this.allLoaded = true;
                  }
              },err => {
                  console.log(err);
              })

          },
          //评价上拉加载
          loadBottom() {
              (this.sentPage.page)++;
              setTimeout(() => {
                  this.getCommentList(this.sentPage);
              }, 20);
              if(this.totalNum == this.list.length) {
                  this.allLoaded = true;
              }
              this.$refs.loadmore.onBottomLoaded();
          },
          //发送评价
          sendComment() {
              if(this.obj.content) {
                  this.$api.post(this.$api.baseURLSchool,"updatedata/live_comment/add",this.obj,r => {
                      console.log(r);
                      if(r.data.ret == 1) {
                          this.isShowMc = false;
                          this.sentPage.page = 1;
                          this.getCommentList(this.sentPag);
                      }
                  },err => {
                      console.log(err);
                  })
              }else {
                  this.$utils._toast("输入不可为空");
              }
          },
          //获取课程详情
          getGradeScore() {
              this.cid = this.$route.query.id;
              this.$api.get(this.$api.baseURLSchool,"select_cid/view_live_room_user/"+this.cid,{},r => {
                  // console.log(r);
                  if(r.data.ret == 1) {
                      this.courseObj = r.data.info;
                  }
              },err => {
                  console.log(err);
              })
          },
          initVideo() {
              var videoObject = {
                  container: '#video', //容器的ID或className
                  variable: 'player', //播放函数名称
                  loaded: 'loadedHandler', //当播放器加载后执行的函数
                  loop: false, //播放结束是否循环播放
                  autoplay: true, //是否自动播放
                  poster: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1516874998976&di=097200de670dd806e9a9016251be2eab&imgtype=jpg&src=http%3A%2F%2Fimg2.imgtn.bdimg.com%2Fit%2Fu%3D1291397622%2C1318481737%26fm%3D214%26gp%3D0.jpg', //封面图片
                  config: '', //指定配置函数
                  debug: true, //是否开启调试模式
                  //flashplayer: true, //强制使用flashplayer
                  drag: 'start', //拖动的属性
                  seek: 0, //默认跳转的时间
                  mobileCkControls:false,//是否在移动端（包括ios）环境中显示控制栏
                  live:true,//是否是直播视频，true=直播，false=点播
                  video: 'http://192.168.0.149:8080/t/tmp/hls/123.m3u8'
              };
              var player = new ckplayer(videoObject);
          
              function loadedHandler() {
                  player.addListener('error', errorHandler); //监听视频加载出错
                  player.addListener('loadedmetadata', loadedMetaDataHandler); //监听元数据
                  player.addListener('duration', durationHandler); //监听播放时间
                  player.addListener('time', timeHandler); //监听播放时间
                  player.addListener('play', playHandler); //监听暂停播放
                  player.addListener('pause', pauseHandler); //监听暂停播放
                  player.addListener('buffer', bufferHandler); //监听缓冲状态
                  player.addListener('seek', seekHandler); //监听跳转播放完成
                  player.addListener('seekTime', seekTimeHandler); //监听跳转播放完成
                  player.addListener('volume', volumeChangeHandler); //监听音量改变
                  player.addListener('full', fullHandler); //监听全屏/非全屏切换
                  player.addListener('ended', endedHandler); //监听播放结束
                  player.addListener('screenshot', screenshotHandler); //监听截图功能
                  player.addListener('mouse', mouseHandler); //监听鼠标坐标
                  player.addListener('frontAd', frontAdHandler); //监听前置广告的动作
                  player.addListener('wheel', wheelHandler); //监听视频放大缩小
                  player.addListener('controlBar', controlBarHandler); //监听控制栏显示隐藏事件
                  player.addListener('clickEvent', clickEventHandler); //监听点击事件
                  player.addListener('definitionChange', definitionChangeHandler); //监听清晰度切换事件
                  player.addListener('speed', speedHandler); //监听加载速度
              }
              function errorHandler() {
                  console.log('出错');
                  changeText('.playerstate', '状态：视频加载错误，停止执行其它动作，等待其它操作');
              }

              function loadedMetaDataHandler() {
                  var metaData = player.getMetaDate();
                  //console.log(metaData)
                  var html = ''
                  //console.log(metaData);
                  if(parseInt(metaData['videoWidth']) > 0) {
                      changeText('.playerstate', '状态：获取到元数据信息，如果数据错误，可以使用延迟获取');
                      html += '总时间：' + metaData['duration'] + '秒，';
                      html += '音量：' + metaData['volume'] + '（范围0-1），';
                      html += '播放器的宽度：' + metaData['width'] + 'px，';
                      html += '播放器的高度：' + metaData['height'] + 'px，';
                      html += '视频宽度：' + metaData['videoWidth'] + 'px，';
                      html += '视频高度：' + metaData['videoHeight'] + 'px，';
                      html += '视频原始宽度：' + metaData['streamWidth'] + 'px，';
                      html += '视频原始高度：' + metaData['streamHeight'] + 'px，';
                      html += '是否暂停状态：' + metaData['paused'];
                  } else {
                      changeText('.playerstate', '状态：未正确获取到元数据信息');
                      html = '没有获取到元数据';
                  }
                  changeText('.metadata', html);
              }
              function playHandler() {
                  //player.animateResume();//继续播放所有弹幕
                  changeText('.playstate', getHtml('.playstate') + ' 播放');
                  window.setTimeout(function() {
                      loadedMetaDataHandler();
                  }, 1000);
                  loadedMetaDataHandler();
              }	
              function seekHandler(state) {
                  changeText('.seekstate', getHtml('.seekstate') + ' ' + state);
              }

              function seekTimeHandler(time) {
                  changeText('.seekstate', getHtml('.seekstate') + ' seekTime:' + time);
              }
              function bufferHandler(buffer) {
                  //console.log(buffer);
                  changeText('.bufferstate', '缓冲：' + buffer);
              }

              function volumeChangeHandler(vol) {
                  changeText('.volumechangestate', '当前音量：' + vol);
              }
              function speedHandler(n) {
                  changeText('.speed', '当前加载速率：' + n);
              }
              function screenshotHandler(obj) {
                  changeText('.screenshot', '图片名称：' + obj['name'] + ',截图对象：' + obj['object'] + ',是否用户保存：' + obj['save'] + ',图片：<img src="' + obj['base64'] + '">');
              }

              function fullHandler(b) {
                  if(b) {
                      html = ' 全屏';
                  } else {
                      html = ' 否';
                  }
                  changeText('.fullstate', getHtml('.fullstate') + html);
                  
              }

              function endedHandler() {
                  changeText('.endedstate', '播放结束');
              }

              function mouseHandler(obj) {
                  changeText('.mouse', '鼠标位置，x：' + obj['x'] + '，y：' + obj['y']);
              }

              function frontAdHandler(status) {
                  changeText('.frontad', getHtml('.frontad') + ' ' + status);
              }
              var zoomNow = 1;

              function wheelHandler(n) {
                  if(n > 0) {
                      if(zoomNow < 5) {
                          zoomNow += 0.1;
                      }
                  } else {
                      if(zoomNow > 0) {
                          zoomNow -= 0.1;
                      }
                  }
                  player.videoZoom(zoomNow);//支持鼠标滚轮控制放大缩小
              }
              function controlBarHandler(show){
                  if(show) {
                      html = ' 显示';
                  } else {
                      html = ' 隐藏';
                  }
                  changeText('.controlBar', getHtml('.controlBar') + html);
              }
              function clickEventHandler(eve){
                  changeText('.clickEvent', getHtml('.clickEvent') + ' '+eve);
              }
              function definitionChangeHandler(num){
                  changeText('.definitionChange', getHtml('.definitionChange') + ',切换清晰度编号'+num);
              }
              var videoChangeNum = 0;

              function seekTime() {
                  var time = parseInt(player.getByElement('.seektime').value);
                  var metaData = player.getMetaDate();
                  var duration = metaData['duration'];
                  if(time < 0) {
                      alert('请填写大于0的数字');
                      return;
                  }
                  if(time > duration) {
                      alert('请填写小于' + duration + '的数字');
                      return;
                  }
                  player.videoSeek(time);
              }

              
              function newVideo() {
                  var videoUrl = player.getByElement('.videourl').value;
                  changeVideo(videoUrl);
              }

              function changeVideo(videoUrl) {
                  if(player == null) {
                      return;
                  }
                  var newVideoObject = {
                      container: '#video', //容器的ID
                      variable: 'player',
                      autoplay: true, //是否自动播放
                      loaded: 'loadedHandler', //当播放器加载后执行的函数
                      video: videoUrl
                  }
                  //判断是需要重新加载播放器还是直接换新地址
                  if(player.playerType == 'html5video') {
                      if(player.getFileExt(videoUrl) == '.flv' || player.getFileExt(videoUrl) == '.m3u8' || player.getFileExt(videoUrl) == '.f4v' || videoUrl.substr(0, 4) == 'rtmp') {
                          player.removeChild();

                          player = null;
                          player = new ckplayer();
                          player.embed(newVideoObject);
                      } else {
                          player.newVideo(newVideoObject);
                      }
                  } else {
                      if(player.getFileExt(videoUrl) == '.mp4' || player.getFileExt(videoUrl) == '.webm' || player.getFileExt(videoUrl) == '.ogg') {
                          player = null;
                          player = new ckplayer();
                          player.embed(newVideoObject);
                      } else {
                          player.newVideo(newVideoObject);
                      }
                  }
              }
          
              function changeText(div, text) {
                  player.getByElement(div).innerHTML = text;
              }

              function getHtml(div) {
                  return player.getByElement(div).innerHTML;
              }
              var zoom = 1;
          },
         
      },
      created() {
          this.init();
          this.getOnline_num(1);
          this.getGradeScore();
          this.getCommentList(this.sentPage);
      },
      mounted() {
          this.showVideo();
          this.initVideo();
      },
      //离开路由触发
      beforeRouteLeave(to,from,next){//记录离开时的位置
          $('#video').hide();
          this.getOnline_num(0);
          next();
      },
  }

</script>
<style lang="scss">
  #video {
      position: absolute !important;
      z-index: 1;
      left: 0;
      top: 0px;
      /* top: 50%; */
      /* bottom: 60px; */
      /* transform: translateY(-50%); */
      width: 100%; 
      height: 300px;
      /* height: calc(100% - 200px);  */
  }
  .pausecenter {
      top: 50%!important;
      left: 50%!important;
      transform: translate(-50%,calc(-50% - 10px))!important;
  }
</style>
